package com.dhms.uikit

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import com.dhms.uikit.databinding.TitleCardviewBinding
import com.google.android.material.card.MaterialCardView

/**
 * A CardView with a custom title.
 *
 * Attributes:
 *
 *     - card_title: set the title text, which need to set using the data binding syntax.
 *     - card_state: set the card state text on the end of title wrapper.
 *     - card_option: set the option to execute when the card state is clicked.
 *     - header_option: set the option to execute when the card header is clicked.
 *     - state_color: set the color of the card state.
 *     - is_full_divider: set the divider padding.
 *     - is_rect_corner: set whether the card's radius is 0 or not.
 *     - state_color: set the color of the state or the state tag background.
 *     - layout_padding_vertical: set whether to show the vertical padding or not.
 *     - layout_padding_vertical: set whether to show the vertical padding or not.
 *     - state_is_tag: set whether the state shows as a tag or not.
 *     - pre_icon: set the title's pre icon.
 *     - pre_index: set the title's pre index.
 *     - title_color: set the title's color.
 *
 * Notice: Some of these attributes should be set using the data binding syntax.
 */
class TitleCardView : MaterialCardView {

    private lateinit var _binding: TitleCardviewBinding
    val binding get() = _binding

    private var layoutPaddingVertical: Boolean = true
    private var layoutPaddingHorizontal: Boolean = true

    private var hasLayoutSet = false

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )


    @SuppressLint("ResourceAsColor", "UseCompatLoadingForDrawables", "PrivateResource")
    private fun init(context: Context, attrs: AttributeSet? = null) {
        strokeWidth = 0

        var isFullDivider = true
        var cardStateColor: Int? = null
        var stateIsTag = false
        var preIcon = 0
        var titleColor = 0
        var isRectCorner = false
        if (attrs != null) {
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.TitleCardView)
            isFullDivider = typedArray.getBoolean(R.styleable.TitleCardView_is_full_divider, true)
            cardStateColor = typedArray.getColor(
                R.styleable.TitleCardView_state_color,
                com.google.android.material.R.color.m3_default_color_primary_text
            )
            layoutPaddingVertical =
                typedArray.getBoolean(R.styleable.TitleCardView_layout_padding_vertical, true)
            layoutPaddingHorizontal =
                typedArray.getBoolean(R.styleable.TitleCardView_layout_padding_horizontal, true)
            stateIsTag =
                typedArray.getBoolean(R.styleable.TitleCardView_state_is_tag, false)
            isRectCorner = typedArray.getBoolean(R.styleable.TitleCardView_is_rect_corner, false)
            preIcon = typedArray.getResourceId(R.styleable.TitleCardView_pre_icon, 0)
            titleColor = typedArray.getInt(R.styleable.TitleCardView_title_color, 0)
            typedArray.recycle()
        }

        _binding = TitleCardviewBinding.inflate(LayoutInflater.from(context))

        binding.root.layoutParams =
            LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)

        if (!isFullDivider) {
            binding.cardDivider.dividerInsetStart =
                resources.getDimension(R.dimen.layout_space).toInt()
            binding.cardDivider.dividerInsetEnd =
                resources.getDimension(R.dimen.layout_space).toInt()
        }

        if (isRectCorner) {
            setBackgroundColor(context.getColorFromAttr(com.google.android.material.R.attr.colorOnPrimary))
        } else {
            background = context.getDrawable(R.drawable.cardview_background)
        }

        if (cardStateColor != null) {
            binding.stateColor = cardStateColor
        }

        binding.stateIsTag = stateIsTag
        binding.titleColor = titleColor

        binding.preIcon = if (preIcon != 0) context.getDrawable(preIcon) else null

        addView(binding.root)
    }

    @SuppressLint("DrawAllocation")
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        if (childCount > 2) {
            throw Exception("Only support one child. You can use a view group containing sub children.")
        }
        super.onLayout(changed, l, t, r, b)
        if (hasLayoutSet) {
            return
        }

        val paddingDimen = resources.getDimension(R.dimen.layout_space).toInt()
        getChildAt(1)?.apply {
            val lp = LayoutParams(layoutParams)
            lp.setMargins(
                if (layoutPaddingHorizontal) paddingDimen else 0,
                getChildAt(0).measuredHeight + if (layoutPaddingVertical) paddingDimen else 0,
                if (layoutPaddingHorizontal) paddingDimen else 0,
                if (layoutPaddingVertical) paddingDimen else 0,
            )
            layoutParams = lp
        }
        hasLayoutSet = true
    }
}